package com.itgy.apigateway.config;

import com.itgy.apiclientsdk.util.SignUtil;
import com.itgy.project.provider.InnerInterfaceInfo;
import com.itgy.project.provider.InnerUserInfo;
import com.itgy.project.provider.InnerUserInterfaceInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;

import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

//全局请求过滤
@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    @DubboReference
    private InnerUserInfo innerUserInfo;

    @DubboReference
    private InnerInterfaceInfo innerInterfaceInfo;

    @DubboReference
    private InnerUserInterfaceInfo innerUserInterfaceInfo;

    private static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1");
    private static final String INTERFACE_HOST = "http://localhost:8888";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1.请求日志
        ServerHttpRequest request = exchange.getRequest();
        log.info("请求唯一标识"+request.getId());
        String url = INTERFACE_HOST+request.getPath().value();
        log.info("请求路径"+url);
        String method = request.getMethod().toString();
        log.info("请求方法"+method);
        log.info("请求查询参数"+request.getQueryParams());
        log.info("请求来源地址"+request.getRemoteAddress());
        log.info("请求来源地址"+request.getLocalAddress().getHostString());
        String hostString = request.getLocalAddress().getHostString();

        ServerHttpResponse response = exchange.getResponse();

        //2.黑白名单 - 白名单
        if(!IP_WHITE_LIST.contains(hostString))
        {
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }

        //3.用户鉴权
        HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst("accessKey");
        String nonce = headers.getFirst("nonce");
        String timestamp = headers.getFirst("timestamp");
        String sign = headers.getFirst("sign");
        String body  = headers.getFirst("body");

        //解决中文乱码
        body = new String(body.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        System.out.println("解决乱码后：" + body);


        //去数据库中拿
//        if(!"90f9e7f9-d3ca-49f9-b1c0-cc7011eddffe".equals(accessKey))
//        {
//
//            log.debug("accessKey");
//            response.setStatusCode(HttpStatus.FORBIDDEN);
//            return response.setComplete();
//        }

        if(Long.parseLong(nonce)>10000)
        {
            log.debug("nonce");
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }
        //时间和当前时间不能超过五分钟
        if(System.currentTimeMillis() - Long.parseLong(timestamp)>5*60*1000)
        {
            log.debug("超时");
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }
        Map<String,String> map = null;

        try {
           map = innerUserInfo.getUserInfoByAccessKey(accessKey);
        } catch (Exception e) {
            log.error("通过accessKey查询用户信息异常"+e);
        }
        if(map == null || map.isEmpty())
        {
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }
        String secretKey = map.get("secretKey");
        String sign1 = SignUtil.getSign(body, secretKey);
        if(!sign1.equals(sign))
        {
            log.debug("sign");
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }
        //4.请求的接口是否存在

        String interfaceId = null;
        try {
            interfaceId  = innerInterfaceInfo.getInterfaceInfoId(url,method);
        }catch (Exception e)
        {
            log.error("查询接口信息异常"+e);
        }
        if(interfaceId == null) {
            response.setStatusCode(HttpStatus.BAD_GATEWAY);
            return response.setComplete();
        }
        //5.请求转发，调用模拟接口
//        预期是等模拟接口调用完成，才记录响应日志、统计调用次数。但现实是 chain.fitter 方法立刻返回了，直到 filter 过滤器 return 后才调用了模拟接口。
        Mono<Void> filter = chain.filter(exchange);

        String userId = map.get("userId");
        return handleResponseLog(exchange,chain,interfaceId,userId);

    }

    public Mono<Void> handleResponseLog(ServerWebExchange exchange, GatewayFilterChain chain,String interfaceId, String userId)
    {
        try {
            //原来的响应
            ServerHttpResponse originalResponse = exchange.getResponse();
            //缓冲区工厂 拿到缓存数据
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            //拿到状态码
            HttpStatus statusCode = originalResponse.getStatusCode();

            if(statusCode == HttpStatus.OK){
                //装饰增强能力
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {

                    //等调用完转发的接口之后才会执行
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        //对象是响应
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            //
                            return super.writeWith(fluxBody.map(dataBuffer -> {

                                // 8.调用成功，接口次数加一 invokeCount;
                               Long interId = Long.parseLong(interfaceId);
                               Long usId = Long.parseLong(userId);
                                try {
                                    innerUserInterfaceInfo.invokeCount(interId.longValue(),usId.longValue());
                                } catch (Exception e) {
                                    log.error("调用次数加一异常"+e);
                                }
                                //那数据
                                byte[] content = new byte[dataBuffer.readableByteCount()];
                                dataBuffer.read(content);
                                DataBufferUtils.release(dataBuffer);//释放掉内存
                                // 构建日志
                                StringBuilder sb2 = new StringBuilder(200);
                                sb2.append("<--- {} {} \n");
                                List<Object> rspArgs = new ArrayList<>();
                                rspArgs.add(originalResponse.getStatusCode());
                                //rspArgs.add(requestUrl);
                                String data = new String(content, StandardCharsets.UTF_8);//data
                                sb2.append(data);
                                log.info(sb2.toString(), rspArgs.toArray());//log.info("<-- {} {}\n", originalResponse.getStatusCode(), data);
                                return bufferFactory.wrap(content);
                            }));
                        } else {
                            //调用失败
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange);//降级处理返回数据
        }catch (Exception e){
            log.error("gateway log exception.\n" + e);
            return chain.filter(exchange);
        }

    }



    @Override
    public int getOrder() {
        return -1;
    }
}
